from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import Book

def all_book(request):
    # 查询所有图书数据
    books = Book.objects.all()
    # print(books)
    # 响应模板，将查询的数据传递给模板
    return render(request, 'bookstore/all_book.html', locals())
def add_book(request):
    if request.method == 'GET':
        return render(request, 'bookstore/add_book.html')
    elif request.method == 'POST':
        # 获取POST参数
        book = request.POST
        # print(book)
        title = book['title']
        pub = book['pub']
        price = book['price']
        market_price = book['market_price']
        # 使用异常处理判断是否插入成功
        try:
            Book.objects.create(title=title, pub=pub, price=price, market_price=market_price)
        except Exception as e:
            print('错误原因：', e)
            return HttpResponse('插入失败')
        else:
            # return HttpResponse('图书新增成功')
            # 跳转到图书列表页  /bookstore/all_book
            return HttpResponseRedirect('/bookstore/all_book')

def update_book(request, book_id):
    # 通过 传递的id查询出图书
    book = Book.objects.get(id=book_id)
    # 如果是GET请求，响应模板文件，把查询的数据显示到表单控件中
    if request.method == 'GET':
        return render(request, 'bookstore/update_book.html', locals())
    # 如果是POST请求，获取表单传递的参数，执行修改
    elif request.method == 'POST':
        info = request.POST
        print(info)
        book.price = info['price']
        book.market_price = info['market_price']
        book.save()
        # 跳转到图书列表页
        return HttpResponseRedirect('/bookstore/all_book')

